package cn.nextProject.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Base64;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtils {

    /**
     * 生成token  header.payload.singature
     */
    private static final String SING = "LIUHE";

    /**
     * 生成Token
     * @return
     */
    public static String getToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        // 默认7天过期
        instance.add(Calendar.DATE, 7);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        // payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        String token = builder.withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256(SING));  // sign
        return token;
    }

    /**
     * 验证token  合法性
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     * 获取token信息方法
     */
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }

    /**
     * token解码
     * @param decodedJWT
     * @return
     */
    public static String getUsernameFromToken(DecodedJWT decodedJWT) {
        try {
            // 解码 Payload
            String payload = decodedJWT.getPayload();
            byte[] decodedPayloadBytes = Base64.getUrlDecoder().decode(payload);
            String decodedPayload = new String(decodedPayloadBytes, StandardCharsets.UTF_8);

            // 解析 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode payloadJson = objectMapper.readTree(decodedPayload);

            String username = payloadJson.path("username").asText();

            // 提取嵌套字段
            return username;
        } catch (Exception e) {
            throw new RuntimeException("JWT解码失败", e);
        }
    }


}
